package com.electric.electric.controller;

import com.electric.electric.Common.JwtProperties;
import com.electric.electric.Common.JwtUtil;
import com.electric.electric.Common.Result;
import com.electric.electric.POJO.DTO.admin.SysUserDTO;
import com.electric.electric.POJO.DTO.admin.UserInfoDTO;
import com.electric.electric.POJO.Entity.admin.SysUser;


import com.electric.electric.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@Slf4j
@RequestMapping("/api/admin")
// 登录请求处理
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 验证密码以及用户名是否对应 成功后下发JWT令牌
     * @param sysUser
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody SysUserDTO sysUser){
        // 获取Redis操作对象
        ValueOperations valueOperations = redisTemplate.opsForValue();
        log.info("后台管理系统用户登录...");

        // 遍历cookies 从Cookies中获取 CaptchaKey
        String adminToken = null;
        Cookie[] cookies= request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("CaptchaKey".equals(cookie.getName())) {
                    adminToken = cookie.getValue();
                    break;
                }
            }
        }
        // 如果未找到 CaptchaKey，返回错误
        if (adminToken == null) {
            return Result.error("验证码已过期，请刷新重试");
        }

        // 从 Redis 中获取验证码
        String verCodeInRedis = (String) valueOperations.get(adminToken);
        if (verCodeInRedis == null) {
            return Result.error("验证码已过期，请刷新重试");
        }

        // 验证用户输入的验证码是否正确
        if (!verCodeInRedis.equalsIgnoreCase(sysUser.getCode())) {
            return Result.error("验证码错误");
        }




        SysUser user = loginService.login(sysUser);
        if(user == null) {
            log.info("验证失败！！！");
            return Result.error("用户名或密码错误");
        }
        log.info("验证成功...");
        // 生成JWT令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId",user.getId());
        claims.put("avatarUrl",user.getAvatarUrl());
        claims.put("username",user.getUsername());

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                user.getUsername(),
                claims);
        return Result.success("登录成功...",token);


    }

    /**
     * 查询用户角色信息
     * @param id
     * @return
     */
    @GetMapping("/getRoleInfo")
    public Result getIRolenfo(@RequestParam Integer id) {
        log.info("查询用户id:{}角色信息...",id);
        UserInfoDTO userInfoDTO = loginService.getInfo(id);
        return Result.success(userInfoDTO);
    }


}
